package com.androidgame.framework.impl;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

//house our game�s main loop
public class AndroidFastRenderView extends SurfaceView implements Runnable 
{
	//keeps a reference to a Game instance from which it can get the active Screen
	AndroidGame game;
	
	Bitmap framebuffer;
	
	Thread renderThread = null;
	
	SurfaceHolder holder;
	
	volatile boolean running = false;
	
	//This should look very familiar. We just need to add two more members: an AndroidGame
	//instance and a Bitmap instance representing our artificial framebuffer. The other
	//members are the same as in our FastRenderView from Chapter 3.
	
	public AndroidFastRenderView(AndroidGame game, Bitmap framebuffer) 
	{
		super(game);
		this.game = game;
		this.framebuffer = framebuffer;
		this.holder = getHolder();
	}
	//In the constructor we simply call the base classs constructor with the AndroidGame
	//parameter (which is an Activity; more on that in a bit) and store the parameters in the
	//respective members. We also get a SurfaceHolder again, as we did previously.
	
	public void resume() 
	{
		running = true;
		renderThread = new Thread(this);
		renderThread.start();
	}
	//The resume() method is an exact copy of the FastRenderView.resume() method, so we
	//don�t need to go over that again. It just makes sure that our thread plays nice with the
	//activity life cycle.
	
	//games main loop
	public void run() 
	{
		Rect dstRect = new Rect();
		
		long startTime = System.nanoTime();
		
		while(running) 
		{
			if(!holder.getSurface().isValid())
			{
				continue;
			}
			
			float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f;
			
			startTime = System.nanoTime();
			
			game.getCurrentScreen().update(deltaTime);
			
			game.getCurrentScreen().present(deltaTime);
			
			Canvas canvas = holder.lockCanvas();
			
			canvas.getClipBounds(dstRect);
			
			canvas.drawBitmap(framebuffer, null, dstRect, null);
			
			holder.unlockCanvasAndPost(canvas);
		}
	}
	
	public void pause() 
	{
		running = false;
		while(true) 
		{
			try 
			{
				renderThread.join();
				break;
			} 
			
			catch (InterruptedException e) 
			{
				// retry
			}
		}
	}
}
